package com.lvcoding.sec3.secdemo3.validatecode.img;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.RandomUtil;
import com.lvcoding.sec3.secdemo3.config.SysConfig;
import com.lvcoding.sec3.secdemo3.validatecode.parent.ValidateCodeGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 图形验证码实现
 */
@Slf4j
@Component
public class ImgCodeGenerator implements ValidateCodeGenerator {

    @Autowired
    private SysConfig sysConfig;

    @Override
    public ImgCode generate(ServletWebRequest request) {
        String code = RandomUtil.randomString(sysConfig.getImgCode().getLength());
        log.debug("图片验证码：{}", code);
        ShearCaptcha lineCaptcha = CaptchaUtil.createShearCaptcha(sysConfig.getImgCode().getWidth(), sysConfig.getImgCode().getHeight());
        Image image = lineCaptcha.createImage(code);
        BufferedImage bufferedImage = ImgUtil.toBufferedImage(image);
        return new ImgCode(code, sysConfig.getImgCode().getExpireIn(), bufferedImage);
    }
}
